package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.constants.wemedia.WmMaterialConstant;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    //oss存储文件的路径 需要加文件名
    @Value("${file.oss.web-site}")
    String website;
    //保存文件的目录
    @Value("${file.oss.prefix}")
    String prefix;

    /**
     * 素材上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //判断是否为空
        if(multipartFile == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //用户上传的文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        //截取文件结尾 判断上传的文件是否 符合要求
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(!checkFileSuffix(suffix)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上传的文件暂不支持");
        }
        //将文件名称+uuid 防止重名覆盖 因为uuid 随机生产的字符串中间有- 这里替换掉
       String filename = UUID.randomUUID().toString().replace("-","");
       filename += suffix;

       //上传文件到oss
        String store = null;
        try {
             store = fileStorageService.store(prefix, filename, multipartFile.getInputStream());
             log.info("文件上传的名称为: {}",store);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //上传好之后 将文件全路径 文件信息 保存在数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(store);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);

        wmMaterial.setUrl(website+store);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 判断 传入的文件后缀名是否 符合要求
     * @param suffix
     * @return
     */
    private Boolean checkFileSuffix(String suffix){
        if(StringUtils.isBlank(suffix)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<String> list = Arrays.asList("jpg","jpeg","png","gif");
        for (String fileName : list) {
            if(suffix.endsWith(fileName)){
               return true;
            }
        }
        return false;
    }

    /**
     * 查询收藏的素材 或 全部查询
     * @param wmMaterialDTO
     * @return
     */
    @Override
    public PageResponseResult findlist(WmMaterialDTO wmMaterialDTO) {
        if(wmMaterialDTO == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录的用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }

        //构建查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId,user.getId());
        if(wmMaterialDTO.getIsCollection().equals(WmMaterialConstant.COLLECT)){
            wrapper.eq(WmMaterial::getIsCollection,WmMaterialConstant.COLLECT);
        }
        //时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        //分页查询
        Page<WmMaterial> page = new Page<>(wmMaterialDTO.getPage(),wmMaterialDTO.getSize());
        IPage<WmMaterial> result = this.page(page,wrapper);
        //利用stream流对集合中的每一个对象都操作将数据库中的地址加上真实地址 前端才能显示
        List<WmMaterial> materialList = result.getRecords().stream().map(wmMaterial -> {
            WmMaterial wmMaterial1 = new WmMaterial();
            BeanUtils.copyProperties(wmMaterial,wmMaterial1);
            wmMaterial1.setUrl(website + wmMaterial.getUrl());
            return wmMaterial1;
        }).collect(Collectors.toList());

        return new PageResponseResult(wmMaterialDTO.getPage(),wmMaterialDTO.getSize(),result.getTotal(),materialList);
    }


    @Override
    public ResponseResult updateCollect(Integer id, Short collect) {
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaUpdateWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaUpdate()
                .eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, collect);
        update(wrapper);
        return ResponseResult.okResult();
    }
}

